<template>
  <view class="realname-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image class="back-icon" src="/static/Images/shop/Fanhuih.png" mode="aspectFit"></image>
      </view>
      <view class="title">实名认证</view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 标题与副标题 -->
      <view class="form-header">
        <view class="form-title">请填写实名认证信息</view>
        <view class="form-subtitle">以保障您的资金账户安全</view>
      </view>

      <view class="form-section">
        <view class="section-title">请确认您的身份信息</view>

        <!-- 姓名 -->
        <view class="input-item">
          <view class="input-label">姓名</view>
          <input class="input-field" type="text" placeholder="请输入本人姓名" v-model="formData.name" />
        </view>

        <!-- 身份证 -->
        <view class="input-item">
          <view class="input-label">身份证</view>
          <input class="input-field" type="idcard" placeholder="请输入本人身份证号" v-model="formData.idCard" />
        </view>

        <!-- 手机号（仅展示，不编辑） -->
        <view class="input-item">
          <view class="input-label">手机号</view>
          <input class="input-field" type="text" :value="formData.phone" disabled />
        </view>
        
        <!-- 验证码 行 -->
        <view class="verification-row">
          <view class="input-item code-box">
            <view class="input-label">验证码</view>
            <input class="input-field" type="number" placeholder="请输入验证码" v-model="formData.code" />
          </view>
          <button class="send-code-btn" :disabled="countdown > 0" @click="sendVerificationCode">
            {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
          </button>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tips-section">
        <view class="tip-title">提示：</view>
        <view class="tip-content">根据我国的反洗钱法和相关法律法规，凡在本平台需要进行卡密寄售服务、代充值服务、商品分销等相关业务的用户，均需要进行实名认证升级成商户，方可正常交易赚取佣金并正常提现，否则将无法将佣金正常提现。</view>
      </view>

      <!-- 协议同意 -->
      <view class="agreement-section" @click="toggleAgreement">
        <view :class="['checkbox', { checked: isAgreed }]" />
        <view class="agreement-text">
          我已阅读并同意 <text class="agreement-link" @click.stop="openAgreement">《XXX平台相关协议&使用规则》</text>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" :class="{ 'btn-disabled': !isFormValid }" :disabled="!isFormValid" @click="submitForm">下一步</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { userApi, smsApi } from '@/utils/api';
import { getUserInfo } from '@/utils/userInfo';

// 表单数据
const formData = ref({
  name: '',
  idCard: '',
  phone: '', // 真实手机号
  code: ''
});

// 是否同意协议
const isAgreed = ref(false);

// 验证码倒计时
const countdown = ref(0);
let timer = null;

// 手机号格式验证
const isValidPhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 身份证格式验证
const isValidIdCard = (idCard) => {
  const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return idCardRegex.test(idCard);
};

// 表单验证：名称/身份证/手机号/验证码 + 勾选协议
const isFormValid = computed(() => {
  return (
    formData.value.name.trim() !== '' &&
    formData.value.idCard.trim() !== '' &&
    isValidIdCard(formData.value.idCard.trim()) &&
    formData.value.phone.trim() !== '' &&
    isValidPhone(formData.value.phone.trim()) &&
    formData.value.code.trim() !== '' &&
    formData.value.code.trim().length >= 4 &&
    isAgreed.value
  );
});

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 切换协议同意状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value;
};

// 打开协议
const openAgreement = () => {
  uni.showToast({
    title: '协议页面开发中',
    icon: 'none'
  });
};

// 发送验证码
const sendVerificationCode = async () => {
  if (countdown.value > 0) return;
  
  if (!formData.value.phone) {
    uni.showToast({ title: '请先获取手机号', icon: 'none' });
    return;
  }
  
  // 验证手机号格式
  if (!isValidPhone(formData.value.phone)) {
    uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' });
    return;
  }
  
  try {
    uni.showLoading({ title: '发送中...' });
    // 发送验证码时传递手机号参数
    await smsApi.sendCode(formData.value.phone);
    uni.hideLoading();
    uni.showToast({ title: '验证码已发送', icon: 'success' });
    
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ 
      title: error?.message || '发送失败，请重试', 
      icon: 'none' 
    });
  }
};

// 提交表单：调用实名认证接口
const submitForm = async () => {
  if (!isFormValid.value) return;
  
  // 额外验证手机号和验证码
  if (!formData.value.phone || !isValidPhone(formData.value.phone)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }
  
  if (!formData.value.code || formData.value.code.trim().length < 4) {
    uni.showToast({ title: '请输入正确的验证码', icon: 'none' });
    return;
  }
  
  try {
    uni.showLoading({ title: '提交中...' });
    // 确保mobile和msgCode参数正确传递
    const requestParams = {
      real_name: formData.value.name.trim(),
      idcard: formData.value.idCard.trim(),
      mobile: formData.value.phone.trim(), // 手机号参数
      msgCode: formData.value.code.trim()   // 验证码参数
    };
    
    console.log('提交实名认证参数:', requestParams); // 调试日志
    
    const response = await userApi.realNameTwo(requestParams);
    uni.hideLoading();
    
    // 检查返回的code是否为0（错误情况）
    if (response?.code === 0) {
      // 解析msg中的message值
      let errorMessage = '认证失败，请重新提交资料';
      
      try {
        // 尝试从msg中提取JSON格式的message
        const msgStr = response.msg || '';
        // 使用正则表达式匹配JSON部分
        const jsonMatch = msgStr.match(/\{[^}]*"message":"([^"]*)"[^}]*\}/);
        if (jsonMatch && jsonMatch[1]) {
          errorMessage = jsonMatch[1];
        } else {
          // 如果没有匹配到JSON格式的message，直接使用msg
          errorMessage = msgStr || errorMessage;
        }
      } catch (error) {
        console.error('解析错误消息失败:', error);
        // 使用默认错误消息
      }
      
      uni.showToast({ 
        title: errorMessage, 
        icon: 'none',
        duration: 3000
      });
      return;
    }
    
    // 检查返回的数据中是否有web_url
    if (response?.data?.web_url) {
      // 提示用户需要刷脸认证
      uni.showModal({
        title: '刷脸认证',
        content: '接下来需要进行刷脸认证，请确保光线充足，点击确定开始认证',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
             // 将webview URL存储到sessionStorage中，避免在URL中暴露
             uni.setStorageSync('webview_url', response.data.web_url);
             
             // 用户确认后跳转到 webview 页面
             uni.navigateTo({
               url: '/pages/common/webview'
             });
           }
        }
      });
    } else {
      // 如果没有web_url，按原来的逻辑处理
      uni.showToast({ title: '认证失败，请检查信息再试', icon: 'success' });
    }
  } catch (err) {
    uni.hideLoading();
    uni.showToast({ title: err?.message || '认证失败', icon: 'none' });
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userInfo = await getUserInfo();
    if (userInfo && userInfo.mobile) {
      formData.value.phone = userInfo.mobile;
    } else if (userInfo && userInfo.phone) {
      formData.value.phone = userInfo.phone;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 组件挂载时获取用户信息并清除定时器
onMounted(() => {
  fetchUserInfo();
  
  return () => {
    if (timer) {
      clearInterval(timer);
    }
  };
});
</script>

<style lang="scss">
.realname-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 导航栏 */
.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  background-color: #ffffff;
  padding-top: var(--status-bar-height, 44px);
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

/* 表单容器 */
.form-container {
  padding: 40rpx 30rpx;
  background-color: #fff;
  margin-top: 0.5rem;
}

.form-header {
  margin-bottom: 60rpx;
}

.form-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.form-subtitle {
  font-size: 28rpx;
  color: #666;
}

.form-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 40rpx;
}

/* 输入项 */
.input-item {
  display: flex;
  align-items: center;
  padding: 24rpx 20rpx;
  background-color: #f7f7f7;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  border: none;
}

/* 取消末项下边框 */
.input-item:last-child {
  border-bottom: none;
}

.input-label {
  width: 160rpx;
  font-size: 30rpx;
  color: #666;
  margin-left: 0;
}

.input-field {
  flex: 1;
  height: 60rpx;
  font-size: 30rpx;
  color: #333;
}

.input-field[disabled] {
  color: #999;
}

/* 验证码行 左输入右按钮 */
.verification-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-box {
  flex: 1;
  margin: 0;
}

.send-code-btn {
  width: 220rpx;
  height: 72rpx;
  line-height: 72rpx;
  background-color: transparent;
  color: #FF3037;
  font-size: 26rpx;
  text-align: center;
  border-radius: 36rpx;
  padding: 0;
  border: 2rpx solid #FF3037;
}

.send-code-btn[disabled] {
  background-color: transparent;
  color: #ccc;
  border-color: #ccc;
}

/* 提示信息 */
.tips-section {
  margin-bottom: 40rpx;
}

.tip-title {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  color: #FF6B35;
}

.tip-content {
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

/* 协议同意 */
.agreement-section {
  display: flex;
  align-items: center;
  margin-bottom: 60rpx;
}

.checkbox-container {
  margin-right: 20rpx;
}

.checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #ccc;
  border-radius: 50%;
  position: relative;
}

.checkbox.checked {
  border-color: #FF3037;
  background-color: #FF3037;
}

.checkbox.checked::after {
  content: '';
  position: absolute;
  left: 12rpx;
  top: 6rpx;
  width: 8rpx;
  height: 16rpx;
  border-right: 4rpx solid #fff;
  border-bottom: 4rpx solid #fff;
  transform: rotate(45deg);
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
}

.agreement-link {
  color: #FF3037;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #FF3037;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  text-align: center;
  margin-top: 40rpx;
}

.submit-btn[disabled],
.btn-disabled {
  background-color: #ccc !important;
  color: #fff !important;
  opacity: 1;
}
</style>